<?php

/**
 * WeEngine System
 *
 * (c) We7Team 2021 <https://www.w7.cc>
 *
 * This is not a free software
 * Using it under the license terms
 * visited https://www.w7.cc for more details
 */

namespace W7\Addons\demo_engine_wechat\Controller;

use W7\App\Controller\BaseController;
use W7\Http\Message\Server\Request;
use W7\Addons\demo_engine_wechat\Model\Entity\News;
use W7\Addons\demo_engine_wechat\Model\Logic\NewsLogic;

class IndexController extends BaseController
{
    public function add(Request $request)
    {
        $validatedData = $this->validate($request, [
            'id' => 'numeric',
        ]);
        $newsInfo = [];
        if (!empty($validatedData['id'])) {
            $newsInfo = News::query()->where('id', $validatedData['id'])->first();
            if (empty($newsInfo)) {
                throw new LogicErrorException('文章不存在！');
            }
        }
        
        return $this->render('@demo_engine_wechat/index/add', ['info' => $newsInfo, 'app_id' => $GLOBALS['container']['app_id']]);
    }

    public function save(Request $request)
    {
        $validatedData = $this->validate($request, [
            'id'          => 'numeric',
            'title'       => 'alpha_dash',
            'label'       => 'alpha_dash',
            'description' => 'alpha_dash',
            'content'     => 'alpha_dash',
        ]);
        NewsLogic::instance()->save($validatedData);
        return wSuccess('保存成功！');
    }

    public function list(Request $request)
    {
        $validatedData = $this->validate($request, [
            'label' => 'alpha_dash',
        ]);

        $menu = NewsLogic::instance()->getMenu();
        if ($menu) {
            $menu = array_column($menu->toArray(), 'label');
        }
        $list = NewsLogic::instance()->lists($validatedData['label'] ?? '');
        return $this->render('@demo_engine_wechat/index/index', ['list' => $list, 'menu' => array_unique($menu)]);
    }

    public function detail(Request $request)
    {
        $validatedData = $this->validate($request, [
            'id' => 'required|numeric',
        ]);
        $newsInfo = News::query()->where('id', $validatedData['id'])->first();
        if (empty($newsInfo)) {
            throw new LogicErrorException('文章不存在！');
        }
        return $this->render('@demo_engine_wechat/index/detail', ['info' => $newsInfo]);
    }

    public function delete(Request $request)
    {
        $validatedData = $this->validate($request, [
            'id' => 'required|numeric',
        ]);
        NewsLogic::instance()->delete($validatedData['id']);
        return wSuccess('删除成功！');
    }
}
